import { CartHeader } from "./components/CartHeader";
import { CartFooter } from "./components/CartFooter";
import { CartItem } from "./components/CartItem";
import "./App.scss";
import { useState, useEffect } from "react";
import axios from "axios";
const http = axios.create({
  baseURL: "http://localhost:8888",
});

const App = () => {
  //渲染
  // 1. data.json文件创建，使用json-server启动服务
  // 2. 安装axios，导入，配置
  // 3. 创建状态
  const [goodsList, setGoodsList] = useState([]);
  // 4. 组件第一次渲染的时候，发送请求获取商品列表，存储商品列表数据
  // 5. 传递给item组件去渲染
  useEffect(() => {
    const loadData = async () => {
      const res = await http.get("/goodsList");
      setGoodsList(res.data);
      // 全选状态：初始化需要设置一下
      setCheckAll(res.data.every((item) => item.goods_state));
    };
    loadData();
  }, []);

  // 修改商品状态
  const onChangeGoodsState = (id, goods_state) => {
    const newList = goodsList.map((item) => {
      if (item.id === id) {
        return { ...item, goods_state };
      } else {
        return item;
      }
    });
    // 改完组件数据
    setGoodsList(newList);
    // 全选状态：单个商品改变状态
    setCheckAll(newList.every((item) => item.goods_state));

    // 调用接口修改数据
    http.patch(`/goodsList/${id}`, { goods_state });
  };

  // 全选逻辑
  const [checkAll, setCheckAll] = useState(false);
  const onChangeCheckAll = (goods_state) => {
    // 修改自己的状态
    setCheckAll(goods_state);
    // 还需要修改所有商品状态
    // 本地
    setGoodsList(goodsList.map((item) => ({ ...item, goods_state })));
    // 接口 (没有批量修改的接口，遍历的去需改)
    Promise.all(
      goodsList.map((item) => {
        return http.patch(`/goodsList/${item.id}`, { goods_state });
      })
    );
  };

  // 计算件数和金额
  const totalCount = goodsList.reduce((prev, item) => {
    if (item.goods_state) {
      return prev + item.goods_count;
    } else {
      return prev;
    }
  }, 0);
  const totalPrice = goodsList.reduce((prev, item) => {
    if (item.goods_state) {
      return prev + item.goods_count * item.goods_price;
    } else {
      return prev;
    }
  }, 0);

  return (
    <div className="app">
      <CartHeader>购物车案例</CartHeader>
      {goodsList.map((item) => (
        <CartItem
          key={item.id}
          {...item}
          onChangeGoodsState={onChangeGoodsState}
        />
      ))}
      <CartFooter
        totalCount={totalCount}
        totalPrice={totalPrice}
        checkAll={checkAll}
        onChangeCheckAll={onChangeCheckAll}
      />
    </div>
  );
};

export default App;
